package com.bdqn.demo04;

import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import org.apache.log4j.Logger;

import java.lang.reflect.Method;

/**
 * CGLIBMethodInterceptor
 *
 * @author LILIBO
 * @since 2021-12-02
 */
public class CGLIBMethodInterceptor implements MethodInterceptor {

    private static final Logger logger = Logger.getLogger(CGLIBMethodInterceptor.class);


    /**
     * 为被代理的方法定义代理业务规则
     */
    @Override
    public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        before(proxy, method, args);
        long start = System.currentTimeMillis();
        Object result = methodProxy.invokeSuper(proxy, args);
        after(start, proxy, method, result);
        return result;
    }

    private void before(Object proxy, Method method, Object[] args) {
        logger.debug("正在调用" + proxy.getClass().getName() + "类的" + method.getName() + "方法，参数是：" + args);
    }

    private void after(long start, Object proxy, Method method, Object result) {
        long end = System.currentTimeMillis();
        logger.debug(proxy.getClass().getName() + "类的" + method.getName() + "方法调用完成（"+(end - start)+"毫秒），返回值是：" + result);

    }

}
